/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008 www.pretty-tools.com
 */

var gLogger = null;
try
{
    gLogger = yrprxFactory.createLogger("wsshOptionsDlg");
}
catch(ex)
{
    dump("Cannot create logger! Exception: " + ex + "\n");
}

function loadOptions()
{
    try
    {
        document.getElementById("delay").value = wsshConfig.slideShowDelay;
        document.getElementById("auto_start").checked = wsshConfig.slideAutoStart;
        document.getElementById("repeat").checked = wsshConfig.repeat;
        document.getElementById("panel_usage").checked = wsshConfig.showPanelOnlyWhenMouseOverIt;
        document.getElementById("min_size").value = wsshConfig.minImageWidth; //TODO: think about different values

        document.getElementById("shrink").checked = wsshConfig.shrinkToFitScreen;
        document.getElementById("zoom").checked = wsshConfig.zoomToFitScreen;

        document.getElementById("scroll_step").value = wsshConfig.imageScrollStep;
        document.getElementById("zoom_step").value = wsshConfig.imageZoomStep;

        document.getElementById("fullscreen_image_links").checked = wsshConfig.fullscreenImageLink;

        var fullscreenRuledImagesElem = document.getElementById("fullscreen_ruled_images");
        if (fullscreenRuledImagesElem) fullscreenRuledImagesElem.checked = wsshConfig.fullscreenRuledImages;
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("loadOptions: ", ex);
    }
}

function onLoad()
{
    try
    {
        loadOptions();
        // init global data
        initRuleTree();
        // load rules
        loadUserRules();
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("onLoad: ", ex);
    }
}

function doError(elem)
{
    yrprxPrompt.alert(document.title, wsshResources["webslideshow.error.enter.correct.value"]);

    elem.focus();

    throw "Invalid value";
}

function checkNumber(elemId)
{
    var elem = document.getElementById(elemId);
    var value = elem.value;

    if (isNaN(value) || (1 * value) <= 0)
        doError(elem);
}

function checkPercent(elemId)
{
    checkNumber(elemId);

    var elem = document.getElementById(elemId);
    var value = 1 * elem.value;

    if (value > 100)
        doError(elem);
}

function onOK()
{
    try
    {
        checkNumber("delay");
        checkNumber("min_size");
        checkNumber("scroll_step");
        checkNumber("scroll_step");
        checkPercent("zoom_step");

        wsshConfig.slideShowDelay = 1 * document.getElementById("delay").value;
        wsshConfig.slideAutoStart = document.getElementById("auto_start").checked;
        wsshConfig.repeat         = document.getElementById("repeat").checked;
        wsshConfig.showPanelOnlyWhenMouseOverIt = document.getElementById("panel_usage").checked;
        wsshConfig.minImageWidth  = 1 * document.getElementById("min_size").value; //TODO: think about different values
        wsshConfig.minImageHeight = 1 * document.getElementById("min_size").value; //TODO: think about different values

        wsshConfig.shrinkToFitScreen = document.getElementById("shrink").checked;
        wsshConfig.zoomToFitScreen = document.getElementById("zoom").checked;

        wsshConfig.imageScrollStep = 1 * document.getElementById("scroll_step").value;
        wsshConfig.imageZoomStep   = 1 * document.getElementById("zoom_step").value;

        wsshConfig.fullscreenImageLink = document.getElementById("fullscreen_image_links").checked;

        var fullscreenRuledImagesElem = document.getElementById("fullscreen_ruled_images");
        if (fullscreenRuledImagesElem) wsshConfig.fullscreenRuledImages = fullscreenRuledImagesElem.checked;

        if (gSaveRules)
        {
            wsshWebProfileSerializer.saveUserProfile(gUserProfile);
            yrprxObserverServiceHelper.notifyObservers(null, WEBSLIDESHOW_UPDATE_RULES_EVENT, null);
        }

        return true;
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("onOK: ", ex);
    }
    return false;
}

function loadUserRules()
{
    try
    {
        gUserProfile = wsshWebProfileSerializer.loadUserProfile();

        updateUserRules();
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("loadUserRules: ", ex);
    }
}

function onImportRule()
{
    try
    {
        var newRules = wsshWebProfileSerializer.loadProfileFromFile();
        if (!newRules)
            return;

        if (wsshRulesImportManager.containsJavaScript(newRules))
        {
            yrprxPrompt.alert(wsshResources["webslideshow.import.title"], wsshResources["webslideshow.import.rules.contains.js"]);
        }

        gUserProfile = wsshWebProfileMergeHelper.merge(gUserProfile, newRules);
        gSaveRules = true;

        updateUserRules();
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("onImportRule: ", ex);
    }
}

function onExportRule()
{
    wsshWebProfileSerializer.exportUserProfile(gUserProfile);
}

function updateButtons()
{
    try
    {
        var exportRule = document.getElementById("export-rule");
        if (exportRule) exportRule.setAttribute("disabled", (gRuleTreeView.rowCount > 0) ? false : true);
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("updateButtons: ", ex);
    }
}

function onPopupContext()
{
    try
    {
        var idx = gRuleTree.currentIndex;
        var notOnRule = (idx < 0 || idx >= gRuleTreeView.rowCount || gRuleTreeView.isContainer(idx));

        document.getElementById("context-remove").hidden = (gRuleTreeView.selection.count <= 0);
        document.getElementById("context-clone").hidden = notOnRule;
        document.getElementById("context-edit").hidden = notOnRule;

        if (notOnRule || isSingleRuleInDomain(idx))
        {
            var elements = ["context-move-separator", "context-move-up", "context-move-down"];
            for (var e in elements)
            {
                document.getElementById(elements[e]).hidden = true;
            }
        }
        else
        {
            document.getElementById("context-move-separator").hidden = false;

            var treeitem = gRuleTreeContentView.getItemAtIndex(idx);

            document.getElementById("context-move-up").hidden = isFirstRule(treeitem);
            document.getElementById("context-move-down").hidden = isLastRule(treeitem);
        }
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("onPopupContext: ", ex);
    }
}

function onAddRule()
{
    try
    {
        var param = {
            domain: "",
            page: new wsshWebPageProfile(),
            ok: false
        };

        var idx = gRuleTree.currentIndex;

        if (idx >= 0 && idx < gRuleTreeView.rowCount)
        {
            var treeitem = gRuleTreeContentView.getItemAtIndex(idx);
            if (yrprxBrowser.hasAttribute(treeitem, "domain_idx"))
            {
                param.domain = gUserProfile[1*treeitem.getAttribute("domain_idx")].domain;
            }
        }

        addRuleDialog(param);
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("onAddRule: ", ex);
    }
}

function onCloneRule()
{
    try
    {
        var idx = getTreeCurrentIndexOrFail();

        var treeitem = gRuleTreeContentView.getItemAtIndex(idx);
        if (!yrprxBrowser.hasAttribute(treeitem, "domain_idx") || !yrprxBrowser.hasAttribute(treeitem, "page_idx"))
            throw "Invalid item";

        var profile = gUserProfile[1*treeitem.getAttribute("domain_idx")];
        var page =  profile.pages[1*treeitem.getAttribute("page_idx")];

        var param = {
            domain: profile.domain,
            page: page.clone(),
            ok: false
        };

        addRuleDialog(param);
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("onCloneRule: ", ex);
    }
}

function addRuleDialog(param)
{
    try
    {
        // show edit dialog
        wsshWindowManager.openRule(param);
        // check result
        if (!param.ok)
            return;

        // add new rule
        addRule(param);
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("addRuleDialog: ", ex);
    }
}

function addRule(rule)
{
    try
    {
        var idx = findDomainIndex(rule.domain);
        if (idx == -1) //new domain rule
        {
            if (gLogger.enabled) gLogger.debug("addRule: Add rule to new domain");

            var profile = new wsshWebDomainProfile(rule.domain, [rule.page]);

            gUserProfile.push(profile);
            createRuleElements(gUserProfile.length-1, profile);

            selectTreeNode(gRuleTreeView.rowCount-1);
        }
        else // add to existent domain
        {
            if (gLogger.enabled) gLogger.debug("addRule: Add rule to existing domain, idx = " + idx);

            var pages = gUserProfile[idx].pages;
            //add to rules
            pages.push(rule.page);
            //reset check sum
            gUserProfile[idx].checksum = null;

            var treeitem = createPageElements(idx, pages.length-1, rule.page);
            appendRuleElements(idx, treeitem);

            selectTreeNode(gRuleTreeContentView.getIndexOfItem(treeitem));
        }
        gSaveRules = true;

        updateButtons();
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("addRule: ", ex);
    }
}

function onEditRule()
{
    try
    {
        var idx = getTreeCurrentIndexOrFail();
        if (gRuleTreeView.isContainer(idx))
            throw "Invalid element";

        var treeitem = gRuleTreeContentView.getItemAtIndex(idx);
        if (!yrprxBrowser.hasAttribute(treeitem, "domain_idx") || !yrprxBrowser.hasAttribute(treeitem, "page_idx"))
            throw "Invalid item";

        var profile = gUserProfile[1*treeitem.getAttribute("domain_idx")];
        var page =  profile.pages[1*treeitem.getAttribute("page_idx")];
        var param = {
            domain: profile.domain,
            page: page,
            mode: "edit",
            ok: false
        };
        // show edit dialog
        wsshWindowManager.openRule(param);
        // check result
        if (!param.ok)
            return;

        //reset check sum
        profile.checksum = null;

        if (param.domain == profile.domain)
            updateRow(idx, page)
        else // rule has changed domain
        {
            if (gLogger.enabled) gLogger.debug("onEditRule: Domain name was changed to: " + param.domain);

            if (countPages(profile.pages) == 1 && findDomainIndex(param.domain) == -1)
            {
                if (gLogger.enabled) gLogger.debug("onEditRule: Rename domain");
                // update domain
                profile.domain = param.domain;

                var parentIndex = gRuleTreeView.getParentIndex(idx);
                updateDomain(parentIndex, param.domain);

                updateRow(idx, page);
            }
            else
            {
                // remove previous rule
                removeRule();
                // add new rule
                addRule(param);
            }
        }
        gSaveRules = true;
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("onEditRule: ", ex);
    }
}

function checkItemsBeforeSwap(treeitem, treeitem2)
{
    if (!treeitem || !treeitem2
            || !yrprxBrowser.hasAttribute(treeitem, "domain_idx") || !yrprxBrowser.hasAttribute(treeitem, "page_idx")
            || !yrprxBrowser.hasAttribute(treeitem2, "domain_idx") || !yrprxBrowser.hasAttribute(treeitem2, "page_idx")
            || treeitem.getAttribute("domain_idx") != treeitem2.getAttribute("domain_idx"))
        throw "Invalid item";
}

function swapData(domainIndex, pageIndex1, pageIndex2)
{
    var profile = gUserProfile[domainIndex];
    // swap data
    var page = profile.pages[pageIndex1];
    profile.pages[pageIndex1] = profile.pages[pageIndex2];
    profile.pages[pageIndex2] = page;
}

function moveRule(index)
{
    try
    {
        var idx = getTreeCurrentIndexOrFail();

        var treeitem = gRuleTreeContentView.getItemAtIndex(idx);
        var treeitem2 = index > 0 ? treeitem.nextSibling : treeitem.previousSibling;
        checkItemsBeforeSwap(treeitem, treeitem2);

        var domainIndex = 1*treeitem.getAttribute("domain_idx");
        var pageIndex1 = 1*treeitem.getAttribute("page_idx");
        var pageIndex2 = 1*treeitem2.getAttribute("page_idx");

        swapData(domainIndex, pageIndex1, pageIndex2);

        var profile = gUserProfile[domainIndex];

        updateRow(idx, profile.pages[pageIndex1]);
        updateRow(idx+index, profile.pages[pageIndex2]);
        selectTreeNode(idx+index);

        gSaveRules = true;
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("moveRule: ", ex);
    }
}

function moveRuleUp()
{
    moveRule(-1);
}

function moveRuleDown()
{
    moveRule(+1);
}

function onKeyPressInTree(event)
{
    try
    {
        event = yrprxBrowser.getEvent(event);

        if (gLogger.enabled) gLogger.debug("onKeyPressInTree: keyCode= " + event.keyCode + ", charCode=" + event.charCode);

        var modifiers = yrprxKeyboardHelper.getKeyboardModifiers(event);
        var keyCode = event.keyCode;

        var handled = true;
        if (keyCode == yrprxKeyboardHelper.VK_INSERT)
        {
            if (!event.shiftKey)
                onAddRule();
            else
                onCloneRule();
        }
        else if (keyCode == yrprxKeyboardHelper.VK_F4)
            onEditRule();
        else if (keyCode == yrprxKeyboardHelper.VK_DELETE)
            removeRule();
        else if (keyCode == yrprxKeyboardHelper.VK_UP && modifiers == yrprxKeyboardHelper.KEY_MASK_ACCEL)
            moveRuleUp();
        else if (keyCode == yrprxKeyboardHelper.VK_DOWN && modifiers == yrprxKeyboardHelper.KEY_MASK_ACCEL)
            moveRuleDown();
        else
            handled = false;

        if (handled && event.stopPropagation)
            event.stopPropagation();

        return handled;
    }
    catch(ex)
    {
        if (gLogger.enabled) gLogger.error("onKeyPressInTree: ", ex);
    }
}

function onHelp()
{
    var tabs = document.getElementById("tabs");
    if (!!tabs && tabs.selectedIndex == 1)
        yrprxWebNavigationHelper.openInNewWindow(wsshConfig.urlHelpRulesPage);
    else
        yrprxWebNavigationHelper.openInNewWindow(wsshConfig.urlHelpSettingsPage);
}
